﻿<%@ Page Language="C#" AutoEventWireup="true" Inherits="System.Web.Mvc.ViewPage<DesignPageViewData>" %>
<script runat="server">

    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        jQueryScriptManager.Current.RegisterSource(Url.Asset("jsc.portal.core"));
        jQueryScriptManager.Current.RegisterSource(Url.Asset("jquery.ui"));
        GenerateHeaders();
    }

    private void GenerateHeaders()
    {
        if (string.IsNullOrEmpty(Page.Header.Title))
        {
            Page.Header.Title = Model.Title;
        }
    }

</script>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!--
//******************************************************************
//** Software development, CMS                                    **
//** JSC Portal                                                   **
//** JSC Projects                                                 **
//** www.jsc-projects.nl                                          **
//******************************************************************
-->
<html xml:lang="en" lang="en">
<head runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <link rel="Stylesheet" type="text/css" href="<%= Url.Asset("jsc.portal.core.css").Replace("&", "&amp;") %>" />
    <link rel="Stylesheet" type="text/css" href="<%= Url.Content(Model.CSS).Replace("&", "&amp;") %>" />
    <link rel="Stylesheet" type="text/css" href="<%= Url.Asset("jsc.portal.designer.css").Replace("&", "&amp;") %>" />
    <link rel="Stylesheet" type="text/css" href="<%= Url.Asset("jsc.portal.core.authenticated.css").Replace("&", "&amp;") %>" />
    <% if (false) { %>
    <script type="text/javascript" src="../../../Content/jQuery/jquery-1.5-vsdoc.js"></script>
    <% } %>
    <!--[if lte IE 7]>
    <style type="text/css">
        html .jqueryslidemenu{height: 1%;} /*Holly Hack for IE7 and below*/
    </style>
    <![endif]-->  
    <script src="<%= Url.Asset("jquery.core").Replace("&", "&amp;") %>" type="text/javascript"></script>  
    <style type="text/css">
        body { min-width: 1280px;}
        .clear { clear:both; font-size:1px; line-height:1px; }
        #container { float:left; width: 975px; }
        #toolbar { position:absolute; top:35px; cursor: move; }
        #trashcan { float:left; width: 300px;}
        #moduleselector { float: left; width: 300px; }
        #buttonbar { width: 300px; height: 60px; }
        input.error { border: 2px solid red; }        
    </style>
</head>
<body>
<jsc:jQueryScriptManager id="scripts" runat="server"></jsc:jQueryScriptManager>
<form id="design-formulier" action="#">
    <div id="container">
        <% Html.RenderPartial(string.Format("{0}/{1}", ViewData.Model.Template.Path, ViewData.Model.Template.ControlName)); %>
    </div>
</form>

<div id="toolbar">
    <div id="buttonbar" class="ui-sortable">
        <h2><%= JSC.Portal.Web.App.Resources.Msg.Action %></h2>
        <%= Html.LinkButtonLeft(JSC.Portal.Web.App.Resources.Msg.ViewCurrentSite, Url.Action("ShowFriendlyUrl", ControllerNames.PORTALENGINE_CONTROLLER, new { language = ViewData.Model.CurrentPage.Language, friendlyurl = ViewData.Model.CurrentPage.FriendlyURL }))%>
        <%= Html.SeperatorLeft() %>
        <%= Html.LinkButtonLeft(JSC.Portal.Web.App.Resources.Msg.PageManagement, Url.Action("Edit", ControllerNames.PORTALPAGES_CONTROLLER, new { id = ViewData.Model.CurrentPage.Id }))%>
        <%= Html.SeperatorLeft() %>
        <%= Html.LinkButtonLeft(JSC.Portal.Web.App.Resources.Msg.Save, "javascript:SavePageLayout()")%>
    </div>
    <div class="clear"></div>
    <div id="moduleselector" class="ui-sortable">
        <h2><%= JSC.Portal.Web.App.Resources.Msg.SelectAModule %></h2>
        <% var test = new Dictionary<string, object>(); test.Add("style", "float:left"); %>
        <%= Html.DropDownList("moduletypeid", (SelectList)ViewData["ModuleTypes"], JSC.Portal.Web.App.Resources.Msg.PleaseMakeAChoice, test)%>
        <%= Html.SeperatorLeft() %>
        <div class="button" id="linkAddModule" style="float:left;"><span><%= JSC.Portal.Web.App.Resources.Msg.AddModuleType %></span></div>
    </div>
    <div class="clear"></div>
    <div id="trashcan" class="ui-sortable">
	    <h2><%= JSC.Portal.Web.App.Resources.Msg.TrashCan %></h2>
	    <p><%= JSC.Portal.Web.App.Resources.Msg.DragModulesHereToDeleteThem %></p>
    </div>
</div>
<div id="modal-container" style="display: none;"></div>

<script type="text/javascript" language="javascript">
(function($) {
    var updateUpDown = function(sortable) {
        $('dl:not(.ui-sortable-helper)', sortable)
		.removeClass('first').removeClass('last')
		.find('.up, .down').removeClass('disabled').end()
		.filter(':first').addClass('first').find('.up').addClass('disabled').end().end()
		.filter(':last').addClass('last').find('.down').addClass('disabled').end().end();
    };

    var moveUpDown = function() {
        var link = $(this),
		dl = link.parents('dl'),
		prev = dl.prev('dl'),
		next = dl.next('dl');

        if (link.is('.up') && prev.length > 0)
            dl.insertBefore(prev);

        if (link.is('.down') && next.length > 0)
            dl.insertAfter(next);

        updateUpDown(dl.parent());
    };

    var addItem = function() {
        var selectedValue = $("#moduletypeid option:selected").val();
        var selectedModuleName = $("#moduletypeid option:selected").text();
        if (selectedValue != '') {
            var url = '<%= Url.Action("GetModuleProperties", ControllerNames.PORTALPAGEDESIGNER_CONTROLLER) %>/?moduleTypeId=' + selectedValue;
            $.get(url, function(data) {
                var sortable = $('#<%= ViewData.Model.DefaultPlaceholder %>');
                var html = '<dl class="sort"><input type="hidden" id="moduleTypeId" value="' + selectedValue + '" /><dt>' + selectedModuleName + '</dt><dd><table border="0"><tbody id="modulesettings">' + data + '</tbody></table></dd></dl>';

                $(sortable).append(html).sortable('refresh');
                updateUpDown(sortable);
            });
        }
    };        

    var emptyTrashCan = function(item) {
        item.remove();
    };

    var sortableChange = function(e, ui) {
        if (ui.sender) {
            var w = ui.item.width();
            ui.placeholder.width(w);
            ui.helper.css("width", ui.item.children().width());
        }
    };

    var sortableUpdate = function(e, ui) {
        if (ui.item[0].id == 'trashcan') {
            emptyTrashCan(ui.item);
        } else {
            updateUpDown(ui.item[0]);
            if (ui.sender)
                updateUpDown(ui.sender[0]);
        }
    };

    $(document).ready(function() {
        $('#toolbar').draggable();
        var toolbarYloc = null;
        var toolbarXloc = null;
        toolbarYloc = parseInt($('#toolbar').css("top").substring(0, $('#toolbar').css("top").indexOf("px")));
        toolbarXloc = parseInt($(window).width() - $('#toolbar').width()) + "px";
        $('#toolbar').css({ left: toolbarXloc });
        $(window).scroll(function() {
            offset = toolbarYloc + $(document).scrollTop() + "px"; 
            $('#toolbar').animate({ top: offset }, { duration: 500, queue: false });
        });
    
        var els = [<%= ViewData.Model.Placeholders %>,'#trashcan'];
        var $els = $(els.toString());

        $("#linkAddModule").bind('click', addItem);
        
        $els.each(function() {
            updateUpDown(this);
        });

        $els.sortable({
            items: '> dl',
            handle: 'dt',
            cursor: 'move',
            //cursorAt: { top: 2, left: 2 },
            opacity: 0.8,
            //helper: 'clone',
            appendTo: 'body',
            //placeholder: 'clone',
            //placeholder: 'placeholder',
            connectWith: els,
            start: function(e, ui) {
                ui.helper.css("width", ui.item.width());
            },
            change: sortableChange,
            update: sortableUpdate
        });
    });
})(jQuery);

function jq(myid){ 
    return myid.replace(/:/g,'\\:').replace(/\./g,'\\.').replace(/\[/g,'\\[').replace(/\]/g,'\\]') ;
};

function SavePageLayout() {
    $('#design-formulier').validate();
    if (!$('#design-formulier').valid())
        return;
    
    var placeholders = $('.ui-sortable');
    var results = new Array();
    var modulePropertiesValues;
    // iterate through all placeholders
    placeholders.each(function() {
        var ph = $(this).attr('id');
        var sections = $(this).find('.sort');
        var section;

        //iterate trough all sections found on specific placeholder
        sections.each(function(i, item) {
            var sid = $(item).attr('id');
            var moduleTypeId = $(item).find('#moduleTypeId').val();
            modulePropertiesValues = new Array();
            var modulepropertiesIndexes = $(item).find(jq('#moduleproperties.Index'));
            modulepropertiesIndexes.each(function(i, indexname) {
                var name = $(indexname).val();
                var idx = jq('#moduleproperties[' + name + '].Value');
                
                var value = $(item).find(idx).val();
                var x = { 'Name': name, 'Value': value };
                modulePropertiesValues.push(x);
            });
            
            // Create DTO and add to array
            var o = { 'SectionId': sid, 'Placeholder': ph, 'Position': i, 'ModuleTypeId': moduleTypeId, 'ModulePropertiesValues': modulePropertiesValues };
            results.push(o);
        });
    });
    // Post DTO to the controller
    var postData = { widgets: results };
    var widgets = results;
    $.ajax({
        url: '<%= Url.Action("SaveOrUpdate", ControllerNames.PORTALPAGEDESIGNER_CONTROLLER, new { id = ViewData.Model.CurrentPage.Id }) %>',
        type: 'POST',
        //dataType: 'json', // removed for jQuery 1.5 the ajaxSubmit has an open bug on it see: http://stackoverflow.com/questions/4957962/ajaxsubmit-in-combination-with-simplemodal-doesnt-fire-succes-delegate
        data: $.toJSON(widgets),
        contentType: 'application/json; charset=utf-8',
        success: function(result) {
            window.location = result.Url;
        }
    });
};

</script>
</body>
</html>